package com.bdbit.ChargingStation.dao.impl;

import com.bdbit.ChargingStation.dao.OrderDao;
import com.bdbit.ChargingStation.entity.ChargingOrder;
import com.bdbit.ChargingStation.entity.bean_order;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Repository
public class order_impl implements OrderDao {

    private final JdbcTemplate jct;

    public order_impl(JdbcTemplate jct) {
        this.jct = jct;
    }

    @Override
    public int updateOrderById(bean_order order) {
        String sql = "UPDATE charging_order SET " +
                "order_id = ?, " +
                "user_id = ?, " +
                "order_year_month = ?, " +
                "status = ?, " +
                "pile_id = ?, " +
                "region_code = ?, " +
                "ele_code = ?, " +
                "charging_kwh = ?, " +
                "unit_price = ?, " +
                "total_amount = ?, " +
                "prepay_amount = ?, " +
                "start_time = ?, " +
                "end_time = ?, " +
                "reported_duration = ?, " +
                "device_start_time = ?, " +
                "device_end_time = ?, " +
                "payment_method = ?, " +
                "payment_time = ?, " +
                "refund_amount = ?, " +
                "refund_time = ?, " +
                "create_date = ?, " +
                "update_date = ?, " +
                "is_deleted = ? " +
                "WHERE id = ?";

        return jct.update(sql,
                order.getOrderId(),
                order.getUserId(),
                order.getOrderYearMonth(),
                order.getStatus(),
                order.getPileId(),
                order.getRegionCode(),
                order.getEleCode(),
                order.getChargingKwh(),
                order.getUnitPrice(),
                order.getTotalAmount(),
                order.getPrepayAmount(),
                order.getStartTime(),
                order.getEndTime(),
                order.getReportedDuration(),
                order.getDeviceStartTime(),
                order.getDeviceEndTime(),
                order.getPaymentMethod(),
                order.getPaymentTime(),
                order.getRefundAmount(),
                order.getRefundTime(),
                order.getCreateDate(),
                order.getUpdateDate(),
                order.getIsDeleted(),
                order.getId()
        );
    }

    @Override
    public int updateOrder(bean_order order) {
        // 简化的更新方法，根据业务需求选择更新字段
        String sql = "UPDATE charging_order SET " +
                "status = ?, " +
                "charging_kwh = ?, " +
                "total_amount = ?, " +
                "prepay_amount = ?, " +
                "end_time = ?, " +
                "reported_duration = ?, " +
                "device_end_time = ?, " +
                "refund_amount = ?, " +
                "refund_time = ?, " +
                "update_date = ? " +
                "WHERE id = ?";

        return jct.update(sql,
                order.getStatus(),
                order.getChargingKwh(),
                order.getTotalAmount(),
                order.getPrepayAmount(),
                order.getEndTime(),
                order.getReportedDuration(),
                order.getDeviceEndTime(),
                order.getRefundAmount(),
                order.getRefundTime(),
                new Date(), // 更新日期设为当前时间
                order.getId()
        );
    }

    @Override
    public int insertOrder(bean_order order) {
        // 防止各种字段为 null 的检查
        if (order.getUnitPrice() == null) {
            order.setUnitPrice(BigDecimal.ZERO);
        }
        if (order.getIsDeleted() == null) {
            order.setIsDeleted(0);
        }
        if (order.getChargingKwh() == null) {
            order.setChargingKwh(BigDecimal.ZERO);
        }
        // 添加prepayAmount的空值检查
        if (order.getPrepayAmount() == null) {
            order.setPrepayAmount(BigDecimal.ZERO);
        }

        // --- 核心修复部分 ---
        // 在插入之前，设置 create_date 和 update_date 为当前时间212
        // 因为它们在你的数据库中是 NOT NULL
        Date now = new Date();
        if (order.getCreateDate() == null) {
            order.setCreateDate(now);
        }
        if (order.getUpdateDate() == null) {
            order.setUpdateDate(now);
        }
        // --- 修复结束 ---

        String sql = "INSERT INTO charging_order (" +
                "order_id, user_id, order_year_month, status, pile_id, " +
                "region_code, ele_code, charging_kwh, unit_price, total_amount, " +
                "prepay_amount, start_time, end_time, reported_duration, " +
                "device_start_time, device_end_time, payment_method, payment_time, " +
                "refund_amount, refund_time, create_date, update_date, is_deleted" +
                ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        return jct.update(sql,
                order.getOrderId(),
                order.getUserId(),
                order.getOrderYearMonth(),
                order.getStatus(),
                order.getPileId(),
                order.getRegionCode(),
                order.getEleCode(),
                order.getChargingKwh(),
                order.getUnitPrice(),
                order.getTotalAmount(),
                order.getPrepayAmount(),
                order.getStartTime(),
                order.getEndTime(),
                order.getReportedDuration(),
                order.getDeviceStartTime(),
                order.getDeviceEndTime(),
                order.getPaymentMethod(),
                order.getPaymentTime(),
                order.getRefundAmount(),
                order.getRefundTime(),
                order.getCreateDate(),
                order.getUpdateDate(),
                order.getIsDeleted()
        );
    }

    @Override
    public int deleteOrderById(Long id) {
        // 逻辑删除而非物理删除
        String sql = "UPDATE charging_order SET is_deleted = 1 WHERE id = ?";
        return jct.update(sql, id);
    }

    @Override
    public bean_order getOrderById(Long id) {
        String sql = "SELECT * FROM charging_order WHERE id = ? AND is_deleted = 0";
        return jct.queryForObject(sql, new BeanPropertyRowMapper<>(bean_order.class), id);
    }

    @Override
    public List<bean_order> getOrdersByCondition(Integer status, String userId) {
        StringBuilder sql = new StringBuilder("SELECT * FROM charging_order WHERE is_deleted = 0");

        if (status != null) {
            sql.append(" AND status = ").append(status);
        }
        if (userId != null && !userId.isEmpty()) {
            sql.append(" AND user_id = '").append(userId).append("'");
        }
        sql.append(" ORDER BY payment_time DESC");

        return jct.query(sql.toString(), new BeanPropertyRowMapper<>(bean_order.class));
    }

    @Override
    public List<bean_order> getOrdersByUser(String userId) {
        String sql = "SELECT * FROM charging_order WHERE user_id = ? AND is_deleted = 0 ORDER BY payment_time DESC";
        return jct.query(sql, new BeanPropertyRowMapper<>(bean_order.class), userId);
    }

    @Override
    public List<bean_order> getOrdersByStatus(int status) {
        String sql = "SELECT * FROM charging_order WHERE status = ? AND is_deleted = 0 ORDER BY payment_time DESC";
        return jct.query(sql, new BeanPropertyRowMapper<>(bean_order.class), status);
    }

    @Override
    public List<bean_order> getAllOrders() {
        String sql = "SELECT * FROM charging_order WHERE is_deleted = 0 ORDER BY payment_time DESC";
        return jct.query(sql, new BeanPropertyRowMapper<>(bean_order.class));
    }

    @Override
    public int updateOrderStatusNotification(bean_order order) {
        // 更新订单状态
        int result = updateOrder(order);

        if (result > 0 && order.getStatus() != null) {
            // 发送状态变更通知
            sendStatusNotification(order);
        }
        return result;
    }

    /**
     * 发送订单状态变更通知
     */
    private void sendStatusNotification(bean_order order) {
        // 实际项目中这里会调用消息服务发送通知
        // 此处仅保留方法签名
    }

    @Override
    public int batchDeleteOrders(List<Long> ids) {
        if (ids == null || ids.isEmpty()) return 0;

        String sql = "UPDATE charging_order SET is_deleted = 1 WHERE id IN (" +
                String.join(",", ids.stream().map(String::valueOf).toArray(String[]::new)) +
                ")";
        return jct.update(sql);
    }

    @Override
    public List<Map<String, Object>> getOrderStatistics() {
        String sql = "SELECT " +
                "status, COUNT(*) AS count, " +
                "SUM(total_amount) AS total_revenue, " +
                "AVG(total_amount) AS avg_order_value, " +
                "SUM(charging_kwh) AS total_kwh, " +
                "status, COUNT(*) AS status_count " +
                "FROM charging_order " +
                "WHERE is_deleted = 0 " +
                "GROUP BY status";

        return jct.queryForList(sql);
    }

    @Override
    public List<Map<String, Object>> getDailyOrderTrend() {
        String sql = "SELECT " +
                "DATE(create_date) AS date, " +
                "COUNT(*) AS order_count, " +
                "SUM(total_amount) AS daily_revenue " +
                "FROM charging_order " +
                "WHERE is_deleted = 0 " +
                "GROUP BY DATE(create_date) " +
                "ORDER BY DATE(create_date) DESC " +
                "LIMIT 7";

        return jct.queryForList(sql);
    }

    // 以下方法在新的订单系统中可能不再需要
    @Override
    public int updateMessageStatus(int id, int type) {
        return 0;
    }

    @Override
    public List<Map<String, Object>> getMessages(String phone, String type) {
        return null;
    }

    @Override
    public List<ChargingOrder> searchOrders(Map<String, Object> params, int offset, int size) {
        return Collections.emptyList();
    }

    @Override
    public long countSearchOrders(Map<String, Object> params) {
        return 0;
    }
}